<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务编号/名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务编号/名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称/编号" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称/编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请选择产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-video-play"
          size="mini"
          @click="handleStart"
          :disabled="single"
        >开始</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          @click="handleCancel"
          :disabled="multiple"
        >取消</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          @click="handleFinish"
          :disabled="single"
        >结束</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh-left"
          size="mini"
          @click="handleWithdraw"
          :disabled="single"
        >撤回</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="workOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" type="index" width="55" align="center" fixed="left" />
      <el-table-column label="工单编号" prop="workOrderCode" align="center" width="150" fixed="left" />
      <el-table-column label="工单名称" prop="workOrderName" align="center" width="150" fixed="left" />
      <el-table-column label="工单进度" align="center" width="250" fixed="left">
        <template slot-scope="scope">
          <div class="progress-container">
             <div class="progress-segment"
                  v-for="(seg, index) in scope.row.progressSegments"
                  :key="index"
                  :style="{ 'background-color': seg.color, 'width': (100 / scope.row.progressSegments.length) + '%' }">
                <el-tooltip class="item" effect="dark" :content="seg.tooltip" placement="top">
                  <span :style="{ color: seg.textColor }">{{ seg.text }}</span>
                </el-tooltip>
             </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="关联计划" prop="planName" align="center" width="120" />
      <el-table-column label="产品名称" prop="productName" align="center" width="120" />
      <el-table-column label="产品编号" prop="productCode" align="center" width="120" />
      <el-table-column label="规格型号" prop="specification" align="center" width="120" />
      <el-table-column label="产品类型" prop="productType" align="center" width="100">
         <template slot-scope="scope">
            <dict-tag :options="dict.type.product_type" :value="scope.row.productType"/>
         </template>
      </el-table-column>
      <el-table-column label="单位" prop="unit" align="center" width="80" />
      <el-table-column label="计划数量" prop="plannedQty" align="center" width="100" />
      <el-table-column label="实际生产数量" prop="actualQty" align="center" width="120" />
      <el-table-column label="计划开工时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.planStartTime) }}
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.planEndTime) }}
        </template>
      </el-table-column>
      <el-table-column label="实际开工时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.actualStartTime) }}
        </template>
      </el-table-column>
      <el-table-column label="实际完工时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.actualEndTime) }}
        </template>
      </el-table-column>
      <el-table-column label="来源单号" prop="sourceDocNo" align="center" width="150" />
      <el-table-column label="状态" align="center" width="100" fixed="right">
        <template slot-scope="scope">
          <el-tag :type="scope.row.statusType">{{ scope.row.statusLabel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleSchedule(scope.row)"
          >排产</el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listWorkOrder, startWorkOrder, cancelWorkOrder, finishWorkOrder, withdrawWorkOrder, scheduleWorkOrder } from "@/api/sc/workOrder";
import { formatDate } from "@/utils/index";

export default {
  name: "ScWork",
  dicts: ['sys_job_status', 'product_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工单表格数据
      workOrderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: undefined,
        planName: undefined,
        productName: undefined,
        status: undefined
      },
      // 状态类型映射
      statusMap: {
        '0': { type: 'info', label: '待排产' },
        '1': { type: 'info', label: '未开始' },
        '2': { type: 'primary', label: '进行中' },
        '3': { type: 'success', label: '已完成' },
        '4': { type: 'warning', label: '已暂停' },
        '5': { type: 'warning', label: '待质检' },
        '6': { type: 'danger', label: '已取消' }
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/work' || to.name === 'ScWork') {
        console.log('生产工单页面路由变化，刷新数据');
        this.getList();
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('生产工单查询参数变化，刷新数据');
          this.getList();
        }
      },
      deep: true
    }
  },
  methods: {
    /** 查询生产工单列表 */
    getList() {
      this.loading = true;
      listWorkOrder(this.queryParams).then(response => {
        this.processWorkOrderData(response.rows);
        this.workOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 处理工单数据，添加进度条和状态类型 */
    processWorkOrderData(workOrders) {
      workOrders.forEach(order => {
        // 添加状态类型和标签
        const statusInfo = this.statusMap[order.status] || { type: 'info', label: '未知状态' };
        order.statusType = statusInfo.type;
        order.statusLabel = statusInfo.label;
        
        // 添加进度条段落
        if (!order.progressSegments) {
          // 根据工序任务生成进度条段落
          if (order.workOrderTasks && order.workOrderTasks.length > 0) {
            order.progressSegments = order.workOrderTasks.map(task => {
              let color = '#f5f5f5';
              let textColor = '#000';
              let text = '0%';
              let tooltip = `工序名称: ${task.processName}\n状态: ${task.statusName}`;
              
              // 智能计算进度百分比（支持虚拟进度）
              let percent = 0;
              if (task.plannedQty && task.plannedQty > 0) {
                const completedQty = task.completedQty || 0;
                
                // 如果有实际完成数量，使用实际进度
                if (completedQty > 0) {
                  percent = Math.floor((completedQty / task.plannedQty) * 100);
                  percent = Math.min(percent, 100);
                } else {
                  // 没有实际完成数量时，根据状态显示虚拟进度
                  if (task.status === '1') percent = 5;   // 已派工：5%虚拟进度
                  if (task.status === '2') percent = 15;  // 进行中：15%虚拟进度
                  if (task.status === '3') percent = 100; // 已完成：100%
                  if (task.status === '5') percent = 95;  // 待质检：95%
                }
              } else {
                // 没有计划数量信息时的虚拟进度
                if (task.status === '1') percent = 5;
                if (task.status === '2') percent = 15;
                if (task.status === '3') percent = 100;
                if (task.status === '5') percent = 95;
              }

              if (task.status === '0') {
                color = '#f5f5f5';
                text = '0%';
              } else if (task.status === '1') {
                color = '#e6a23c';
                textColor = '#fff';
                text = percent > 0 ? percent + '%' : '已派工';
              } else if (task.status === '2') {
                color = '#409eff';
                textColor = '#fff';
                text = percent > 0 ? percent + '%' : '进行中';
              } else if (task.status === '3') {
                color = '#67c23a';
                textColor = '#fff';
                text = '✓';
              } else if (task.status === '4') {
                color = '#f56c6c';
                textColor = '#fff';
                text = '暂停';
              } else if (task.status === '5') {
                color = '#f39c12';
                textColor = '#fff';
                text = percent > 0 ? percent + '%' : '待质检';
              }
              
              return { color, textColor, text, tooltip };
            });
          } else {
            // 没有工序任务时，根据工单状态生成简单进度条
            let color = '#f5f5f5';
            let textColor = '#000';
            let text = '0%';
            let tooltip = `任务状态: ${order.statusLabel}`;
            
            if (order.status === '0' || order.status === '1') {
              color = '#f5f5f5';
              text = '0%';
            } else if (order.status === '2') {
              color = '#409eff';
              textColor = '#fff';
              text = '进行中';
            } else if (order.status === '3') {
              color = '#67c23a';
              textColor = '#fff';
              text = '✓';
            } else if (order.status === '4') {
              color = '#f56c6c';
              textColor = '#fff';
              text = '暂停';
            }
            
            order.progressSegments = [{ color, textColor, text, tooltip }];
          }
        }
      });
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.workOrderId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 开始按钮操作 */
    handleStart() {
      const workOrderId = this.ids[0];
      this.$modal.confirm('确认要开始该工单吗？').then(() => {
        return startWorkOrder(workOrderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("开始操作成功");
      }).catch(() => {});
    },
    /** 取消按钮操作 */
    handleCancel() {
      const workOrderIds = this.ids;
      this.$modal.confirm('确认要取消选中的工单吗？').then(() => {
        return cancelWorkOrder(workOrderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消操作成功");
      }).catch(() => {});
    },
    /** 结束按钮操作 */
    handleFinish() {
      const workOrderId = this.ids[0];
      this.$modal.confirm('确认要结束该工单吗？').then(() => {
        return finishWorkOrder(workOrderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("结束操作成功");
      }).catch(() => {});
    },
    /** 撤回按钮操作 */
    handleWithdraw() {
      const workOrderId = this.ids[0];
      this.$modal.confirm('确认要撤回该工单吗？').then(() => {
        return withdrawWorkOrder(workOrderId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回操作成功");
      }).catch(() => {});
    },
    /** 排产按钮操作 */
    handleSchedule(row) {
      this.$router.push({ 
        path: '/sc/work/scheduling', 
        query: { 
          workOrderId: row.workOrderId,
          workOrderCode: row.workOrderCode
        } 
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$router.push({
        path: '/sc/work/detail',
        query: {
          workOrderId: row.workOrderId,
          workOrderCode: row.workOrderCode
        }
      });
    },
    /** 格式化日期时间 */
    formatDate(cellValue) {
      return formatDate(cellValue);
    }
  }
};
</script>

<style scoped>
.progress-container {
  display: flex;
  width: 100%;
  height: 20px;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.progress-segment {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  text-align: center;
  transition: width 0.3s ease;
  white-space: pre-wrap;
  word-break: break-all;
}

.progress-segment:not(:first-child) {
    border-left: 1px solid #ebeef5;
}
</style> 